<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>       
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="${_resources}/logo.png"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">                                            
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />  
<title>项目模板类型定义</title>
<%@ include file="/WEB-INF/jsp/common/inc.jsp" %>
<script type="text/javascript" src="${_resources}jquery-ui/jquery-ui-1.10.4.custom.min.js"></script>
<link rel="stylesheet" href="${_resources}jquery-ui/jquery-ui-1.10.4.custom.min.css" />
<style type="text/css">
body{	
	overflow:hidden;
}
</style>
<script type="text/javascript">
var selectDoc ;
var selectedList = new Array();
//新增适用范围
function selectCreate(value){
	if(value=="newCreate"){
		/* $("#popIframe").empty();	
		$("#popDiv").dialog({
			title:'创建项目模板类型',
			autoOpen: true,
			modal: true,	
			height: 300,
			width: 450
		});	
		$("#popIframe").attr("width","100%");
		$("#popIframe").attr("height","95%");
		$("#popIframe").attr("src","${_baseUrl}/applicableScopeController/newApplicableScope");	 */	
		layerIndex =layer.open({
			  type: 2, 
			  title:'创建项目模板类型',
			  area: ['450px', '300px'],
			  fixed: false, //不固定
			  maxmin: true,
			  shim: true,
			  content: "${_baseUrl}/applicableScopeController/newApplicableScope?rand="+Math.random()
			});
	}
}

function getApplicationScope(){
	var path="${_baseUrl}/applicableScopeController/SelectAllApplicableScope";
	$.ajax({    
		type: "POST",    
		async: false,    
		url:path,
		dataType:"json",    
		success: function (data) {   
			var jsonObj=eval("("+data.message+")");
			var options="";
			if(jsonObj.length>0){
				options+="<option>请选择</option>";
				$.each(jsonObj, function (i, item) {
					options+="<option value='"+item.scopeName+"'>"+item.scopeName+"</option>";
			 	});
			}
			options+="<option value='newCreate'>新建适用范围</option>";
			$("#applicationScope").html(options);
			
		}   
	}); 		
	
}



//验证样式输出文档
function checkSelectOut(){	
	var select = $("select[name='styleOutTemplate']");
	var options = $(select).find("option");
	for(var i =0;i<options.length;i++){
		if($(options[i]).prop("selected")=="selected"||$(options[i]).prop("selected")==true){
			var value = $(options[i]).val();
			if(value=="请选择"){
				return "请选择样式模板名称";
			}else{
				return true;
			}
		}
	}
	
}
//验证样式定义文档
function checkSelectSet(){	
	var select = $("select[name='styleSetTemplate']");
	var options = $(select).find("option");
	for(var i =0;i<options.length;i++){
		if($(options[i]).prop("selected")=="selected"||$(options[i]).prop("selected")==true){
			var value = $(options[i]).val();
			if(value=="请选择"){
				return "请选择样式定义模板";
			}else{
				return true;
			}
		}
	}
	
}
//验证适用范围的下拉框
function checkSelectScope(){	
	var select = $("select[name='applicationScope']");
	var options = $(select).find("option");
	var value="";
	for(var i =0;i<options.length;i++){
		if($(options[i]).prop("selected")=="selected"||$(options[i]).prop("selected")==true){
			value = $(options[i]).val();
			
		}
	}

	if(value=="请选择"){
		return "请选择适用范围";
	}else{
		return true;
	}
}


//选中复选框之后将文档id存储到input中，提交到后台去
function selectDocument(){	
	var inputs =$("input:checked");
	var documentId ="";
	for(var i =0;i<inputs.length;i++){
		if(documentId.length==0){
			documentId=$(inputs[i]).val();
		}else{
			documentId+=","+$(inputs[i]).val();
		}
	}	
	
	$("#documentId").val(documentId);
	
}

//取消和关闭调用的方法
function cancelAndClose(){
	parent.closeWin();
}

$(function(){
	$("#form").validationEngine({
		autoHidePrompt:true,//自动隐藏
		showOnMouseOver:true,//当鼠标移出时触发
		promptPosition:'bottomLeft',//提示信息的位置
		inlineValidation: true,//是否即时验证，false为提交表单时验证,默认true  
		failure : function() {
		    layer.message("验证失败，请检查");
			return false;  
		},//验证失败时调用的函数
		ajaxFormValidation: true,//开始AJAX验证
		success : function() {
		//	$("#addForm").submit();
		}//验证通过时调用的函数 
		//onAjaxFormComplete: ajaxValidationCallback
	});
	if(document.getElementById("kdDocument").style.display="block"){
		document.getElementById("input").style.display="none";
	}
})

function formSubmit(){
	var options = {
			dataType:"json",
			success:function(json){
				layer.msg(json.message,{shift:5,time:1500},function(){
					parent.closeWin();
					parent.refreshTable();
					parent.addDemandTrace1(json.data); 
					if(typeof(parent.parent.AgainGetProjectTemplate) != "undefined"){
						parent.parent.AgainGetProjectTemplate();
					}
				});
			},
			error:function(json){
				layer.msg("系统错误,请联系管理员");
			}
		};
	
	if($("#form").validationEngine('validate')){
		var objects = selectedList;
		var stageId = "";
		var documentId ="";
		if(objects.length>0){
			 for(var i =0;i<objects.length;i++){
					if(documentId.size==0){
						documentId=objects[i].documentId;
						stageId = objects[i].stageId;
					}else{
						documentId+=","+objects[i].documentId;
						stageId += ","+objects[i].stageId;
					}
				}
			$("#stageId").val(stageId);
			$("#documentId").val(documentId);
			$("#projectTypeId").val($("#projectType").val());
		 }
		 var documentId=$("#documentId").val();
		if(documentId.length>0){
			$("#submit").attr("onclick","");
			$('#form').ajaxSubmit(options);
		}else{
			layer.msg("请至少选择一个文档模板。");
		}
	}
}
/* 关闭弹出框 */
function closeWin(){
	layer.close();
	//$("#popDiv").dialog('close');
}

function refreshTable(){
	menuList.bootstrapTable('refresh');
}
//点击文档名称查看文档内容
function checkFun(id){
	/* $("#popIframe").empty();	
	$("#popDiv").dialog({
		title:'查看文档模板信息',
		autoOpen: true,
		modal: true,	
		height: 500,
		width: 800
	});	
	$("#popIframe").attr("width","100%");
	$("#popIframe").attr("height","95%");
	$("#popIframe").attr("src","${_baseUrl}/documentTemplateController/checkDocumentTemplatePage?id="+id); */
	layerIndex =layer.open({
		  type: 2, 
		  title:'查看文档模板信息',
		  area: ['800px', '500px'],
		  fixed: false, //不固定
		  maxmin: true,
		  shim: true,
		  content:"${_baseUrl}/documentTemplateController/checkDocumentTemplatePage?id="+id+"&rand="+Math.random()
		});
}

function judgeName(){
	var path="${_baseUrl}/projectTemplateTypeController/judgeProTemplateName";
	var name = $("#projectTemplateName").val();
	if(name !=""){
		$.ajax({    
			type: "POST",    
			async: false,    
			url:path,
			data:{
				"proName":name
				
			},
			dataType:"json",    
			success: function (json) {   
				if(json.code=="1"){
					layer.msg("模板名称已经存在");
					$("#projectTemplateName").val("");
				}
			}   
		});
	}
}

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

$(function(){
	$("#selectByTemplateName").keydown(function(event) {//给输入框绑定按键事件
	    if(event.keyCode == "13") {//判断如果按下的是回车键则执行下面的代码
	    	selectSearch();
	  	}
	})
})

function selectSearch(){
	//var docObj  = "${listDocumentTemplate }";
	var name  = $("#selectByTemplateName").val();
	var source =$("#document_source").val();
	var path ="${_baseUrl}/KmProjectDocumentTemplateController/searchByNameSource";
	var options="";
	$.ajax({    
		type: "POST",    
		async: false,    
		url:path,
		data:{
			"name":name,
			"source":source
		},
		dataType:"json",    
		success: function (json) {  
	       if(json.code=="1"){
				var docObj = eval(json.message);
				$.each(docObj, function (i, item){
					if(judgeSelect(item.id)){
						options +="<tr> <td><input name ='document' value="+item.id+" onclick='judgeSelectDoc(this);'  type ='checkbox' checked='checked' /></td>";
					}else{
						options +="<tr> <td><input name ='document' value="+item.id+" onclick='judgeSelectDoc(this);'  type ='checkbox' /></td>";
					}
					options +="<td>"+(i+1)+"</td>";
					options +="<td>"+item.documentTemplateName+"</td>";
					options +="<td>"+item.documentType+"</td>";
					options +="<td>"+item.applicationScope+"</td>";
					var docSource = item.source;
					if(docSource =="初始化"){
						options +="<td>组织级文档模板</td>";
					}
					if(docSource =="自定义"){
						options +="<td>用户级文档模板</td>";
					}
					if(docSource =="文档范本库"){
						options +="<td>文档范本库</td>";
					}
					options +="</tr>";
				})
				//var size = $(".tablebox thead tr:first-child>td").length;
				var size =$("#documentTb thead tr:first-child>td").length;
				if( options == ''){
					options = "<tr><td colspan="+size+" align='center'>没有符合条件的记录</td></tr>";    /* 当搜索条件为空时给出提示  */
				}
				$("#docList").html(options);
		       document.getElementById("input").style.display="none";
			}
		}  
	});
}

function judgeSelect(id){
	var result = false;
	if($("#documentId").val().indexOf(id)>=0){
		result = true;
	}
	return result;
	
}



function judgeSelectDoc(obj){
	var documentId = $("#documentId").val();
	var inputId = $(obj).val();
	if($(obj).prop("checked")==true){
		if(documentId.indexOf(inputId)>=0){
			return;
		}else{
			$("#documentId").val(documentId+","+inputId);
		}
	}else{
		if(documentId.indexOf(inputId)>=0){
			$("#documentId").val(documentId.replace(inputId,""));
		}else{
			return;
		}
	}
}


//根据项目类型选择项目模板
function selectDocumentTemplateList(){
	var projectType=$("#projectType").find("option:selected").val();
	selectedList.length = 0;
    $("#documentId").val("");
    $("#stageId").val("");
    $("input:checkbox[name='document']").prop("checked", "");
	$("#secretInvolvedLevelList").bootstrapTable('refresh', {url: '${_baseUrl}/KmProjectDocumentTemplateController/selectDocumentTemplateByProjectType' });
	if(projectType != null && projectType != "" && projectType != undefined && projectType != "请选择"){
		document.getElementById("kdDocument").style.display="none";
		document.getElementById("kdDocument1").style.display="none";
		document.getElementById("ktDocument").style.display="block";
		document.getElementById("input").style.display="block";
		secretInvolvedLevelList=$("#secretInvolvedLevelList").bootstrapTable({
			url : '${_baseUrl}/KmProjectDocumentTemplateController/selectDocumentTemplateByProjectType?projectType='+projectType+"&rand="+Math.random(),
			pagination: true,
			pageList: [5, 10, 20, 50],
	  		queryParams: queryParams,
	  		clickToSelect: false,
			onCheck: function(row){
				var ids = new Array();
				for(var i = 0;i<selectedList.length;i++){
					if(selectedList[i] != undefined){
						ids.push(selectedList[i].id);
					}            		
				}
				var idsString = ids.join(",");
				if(!(idsString.indexOf(row.id)>=0)){
					selectedList.push(row);
				}				
			},
			onUncheck: function(row){
				for(var i = 0;i<selectedList.length;i++){
					if(selectedList[i] != undefined){
						if(row.id = selectedList[i].id){
							selectedList.splice(i,1);            		
						}
					}
				}
			},
			onCheckAll: function(rows){
				//var selected = $("#testItemList").bootstrapTable("getSelections");
				var selected = this.data;
				var ids = new Array();
				for(var i = 0;i<selectedList.length;i++){
					if(selectedList[i] != undefined){
						ids.push(selectedList[i].id);
					}
				}
				var idsString = ids.join(",");
				for(var j = 0;j<selected.length;j++){
					if(!(idsString.indexOf(selected[j].id)>=0)){
						selectedList.push(selected[j]);
					}
				}
			},
			onUncheckAll: function(rows){   
				//如何获取已经取消的行
				var selected = this.data;
				var ids = new Array();
				for(var i = 0;i<selected.length;i++){
					ids.push(selected[i].id);
				}
				var idsString = ids.join(",");
				for(var j = 0;j<selectedList.length;j++){
					if(selectedList[j] != undefined){
						if(idsString.indexOf(selectedList[j].id)>=0){
							delete selectedList[j]; 
						}
					}            		
				}
			},
	        columns: [{
				 field: 'checked',
				 checkbox: true,
				 width: 30,
				 height: 50,
				 align: 'center',
				 formatter: function(value, row, index){
						var ids = new Array();
						for(var i = 0;i<selectedList.length;i++){
							if(selectedList[i] != undefined){
								ids.push(selectedList[i].id);
							}                 		
						}
						var idsString = ids.join(",");
						 if(idsString.indexOf(row.id) >= 0){
							return true;
						 }else{
							return false;
						 }
					 }
			 }, {
	            field: 'documentId',
	            title: 'documentId',
	            visible:false,
	            width: 5
	        },{
	            field: 'documentName',
	            title: '文档模板名称',
	            width: 200
	        },{
	            field: 'templateSortKTs',
	            title: '模板类型',
	            width: 100,
	            formatter : function(value, row, index){
	           if(row.templateSortKTs != null && row.templateSortKTs.length > 0 ){
	                		var typeStr = "";
	                		for(var i = 0; i  < row.templateSortKTs.length; i ++){
	                			if(row.templateSortKTs[i].sortName != null){
	                				typeStr += row.templateSortKTs[i].sortName+";";
	                			}
	                		}
	                		typeStr1 = typeStr.substring(0,typeStr.length-1);
	                		return typeStr1;
	            	}
	            		
	            	}
	        },{
	            field: 'applicationScope',
	            title: '文档适用范围',
	            width: 100
	        },{
	            field: 'projectTypeName',
	            title: '项目类型',
	            width: 110
	        },{
	            field: 'stageName',
	            title: '阶段名称',
	            width: 100
	        }, {
	            field: 'stageId',
	            title: 'stageId',
	            visible:false,
	            width: 5
	        }]
	    });
	}else{
		document.getElementById("ktDocument").style.display="none";
		document.getElementById("kdDocument").style.display="block";
		document.getElementById("kdDocument1").style.display="block";
		document.getElementById("input").style.display="none";
	}
}
function queryParams(params){
	return {
	    pageSize: params.limit,
	    pageNo: params.pn,
	    sort : params.sort,
	    order : params.order,
	    projectType:$("#projectType").val(),
	    documentName  : $("#selectByTemplateName1").val()
   };
} 
function selectSearchKT(){
	secretInvolvedLevelList.bootstrapTable('refresh');
}
</script>
<style type="text/css">
.roleshux{width:100%}
.table-bordered > thead > tr > th, .table-bordered > thead > tr > td{border-bottom-width: 1px;}
.submenu_table tbody tr td{text-align: center;}
</style>
</head>
<body>
<form action="${_baseUrl}/KmProjectDocumentTemplateController/saveProjectTemplate" method="post" name="form" id="form">  
 <input type="hidden" name="token" value="${token}" />
 <input type="hidden" name="documentId" id="documentId" value="" />
 <input type="hidden" name="stageId" id="stageId" value="" />
  <input type="hidden" name="projectTypeId" id="projectTypeId" value="" />
 <div class="jbinformation roleshux">
	<table class="table table-bordered submenu_table">
  <tr>
  	<td height="50" width="15%" align="center"><span style="color:#f00">*</span> 模板名称</td>
    <td width="35%" valign="middle">
    <div>
    <input type="text" name="projectTemplateName" id="projectTemplateName" onblur="judgeName();" class="nav_input validate[required,maxSize[50]]">
    </div>
    </td>
    <td height="50" width="15%" align="center"><span style="color:#f00">*</span> 适用范围</td>
    <td width="35%" valign="middle">
    <div>
    <select class="func_select  validate[required,funcCall[checkSelectScope]] "  name="applicationScope" id="applicationScope"  style="width:100%;margin:0;" onchange="selectCreate(this.options[this.options.selectedIndex].value)">
          <option>请选择</option>
         <c:forEach items="${listApplicableScope}" var="applicableScope">
			 <option  value="${applicableScope.id}">${applicableScope.application} </option>
		</c:forEach> 
      </select>
      </div>
      </td>
      </tr>
      <tr>
      <td height="50" width="15%" align="center"><span style="color:#f00">*</span> 样式模板名称</td>
      
    <td width="35%" valign="middle">
    <div>
    <select class="func_select  validate[required,funcCall[checkSelectOut]]"   name="styleOutTemplate" style="width:100%;margin:0;">
           <option>请选择</option>
          <c:forEach items="${listStyleTemplateDefine }" var="styleOutTemplate">
			<c:if test="${styleOutTemplate.styleType=='outSet'}">
				<option  title="${styleOutTemplate.styleDocumentName}" value="${styleOutTemplate.id}">${styleOutTemplate.styleDocumentName}</option>
			</c:if>
		</c:forEach>
      </select>
      </div>
      </td>
       <td height="50" width="15%" align="center">项目类型</td>
        <td width="35%" valign="middle">
            <select name="projectType" id="projectType" onchange="selectDocumentTemplateList();" class="layout_table_select validate[]">
                 <option value = "">请选择</option>
                 <c:forEach items="${listProjectType }" var="listProjectType">
				 <option  title="${listProjectType.name}" value="${listProjectType.id}">${listProjectType.name}</option>
		         </c:forEach>
            </select>
        </td>
  </tr>
</table>
<div class="func_bar" id="kdDocument">
    	<div class="search_container">
	        <div class="func_search">
	        	<div class="func_search_div"></div>
	            <input type="text" id="selectByTemplateName" name="user_date" value="${searchValue}" placeholder="请输入关键词" />
	            <a class="search_btn" onclick="selectSearch();" id="search" href="javascript:;"></a>
	        </div>
	    </div>
        <c:if test="${customCode ne 'huayin'}">
            <select  class="func_select" id="document_source" onchange="selectSearch();" style="width:200px;margin-left:20px;">
                <option value="choice">请选择文档模板来源</option>
                <option value="1">组织级文档模板</option>
                <option value="2">用户级文档模板</option>
                <option value="3">文档范本库</option>
            </select>
        </c:if>
    </div>
</div>
<div id="kdDocument1">
<divstyle="text-align: center;">
    <table id="documentTb" class="table table-bordered submenu_table">
        <thead>
          <tr>
            <td width="5%" align="center">选择</td>
            <td width="10%" align="center">序号</td>
            <td width="22%" align="center">文档模板名称</td>
            <td width="22%" align="center"><span >模板类型</span></td>
            <td width="12%" align="center"><span >适用范围</span></td>
            <td width="22%" align="center">文档模板来源</td>
          </tr>
         </thead>
         <tbody id = "docList">
         <c:forEach items="${listDocumentTemplate }" var="documentTemplate" varStatus="status">
			<tr>
			<td align="center"><input name="document" value="${documentTemplate.id}" onclick="judgeSelectDoc(this);"   type="checkbox"  /></td>
			<td align="center">${status.count}</td>
			<td align="center">${documentTemplate.documentTemplateName}</td>
			<td align="center">${documentTemplate.documentType}</td>
			<td align="center">${documentTemplate.applicationScope}</td>
			<td align="center"><c:if test="${documentTemplate.source=='初始化'}">组织级文档模板</c:if>
				<c:if test="${documentTemplate.source=='自定义'}">用户级文档模板</c:if>
				<c:if test="${documentTemplate.source=='文档范本库'}">文档范本库</c:if></td>
			</tr>
		</c:forEach>
		</tbody>
    </table>
    </div>
</div>
<div style="overflow: auto; width:98%;margin: auto;" id="ktDocument">
<div id="input" class="search_container">
	        <div class="func_search">
	        	<div class="func_search_div"></div>
	            <input type="text" id="selectByTemplateName1" name="user_date" value="${searchValue}" placeholder="请输入关键词" />
	            <a class="search_btn" onclick="selectSearchKT();" id="search" href="javascript:;"></a>
	        </div>
</div>
<table id="secretInvolvedLevelList" class="table table-bordered table_inline"></table>
</div>
<div class="permission_an mubanclass_an ma mt30" style="margin-top:0px;margin-bottom: 10px;">
	<shiro:hasPermission name="KmProjectDocumentTemplateController:saveProjectTemplate">
       <a href="javascript:;"  id="submit"  onclick="formSubmit();" class=" per_baocun">确 定</a>
    </shiro:hasPermission>

	<shiro:hasPermission name="KmProjectDocumentTemplateController:close4">
    <a href="javascript:;" class=" per_gbi" onclick="cancelAndClose();">取 消</a>
    </shiro:hasPermission>

</div>
 <div id="popDiv" style="display: none;">
		<iframe id="popIframe" border="0" frameborder="no"></iframe>
	</div>                             	  	
</form>
</body>
</html>